﻿using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Interactivity;
using FluentAvalonia.UI.Controls;
using iOSClub.App.Desktop.Controls;
using iOSClub.App.Desktop.ProjectDialogs;
using iOSClub.App.Desktop.ViewModels.ProjectPages;
using iOSClub.App.Desktop.Views;
using iOSClub.App.Share;
using iOSClub.App.Share.Serves;

namespace iOSClub.App.Desktop.ProjectPages;

public partial class ProjectView : UserControl
{
    public ProjectView()
    {
        InitializeComponent();
    }

    protected override void OnInitialized()
    {
        if (DataContext is not ProjectViewModel model) return;
        if (model.Projects.Count == 0)
        {
            Content = new EmptyControl("当前无项目");
            return;
        }

        model.Project = model.Projects[0];
    }

    private async void AddTaskClick(object? sender, RoutedEventArgs e)
    {
        var main = ViewOpera.GetView<MainView>(this);
        if (main == null) return;
        var view = ViewOpera.GetView<MainWindow>(main);
        if (view == null) return;
        if (DataContext is not ProjectViewModel model) return;
        var td = new TaskDialog
        {
            Title = "添加任务",
            Content = new AddOrChangeTask(),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CloseButton
            },
            XamlRoot = (Visual)VisualRoot!
        };

        td.Closing += async (dialog, args) =>
        {
            if ((TaskDialogStandardResult)args.Result != TaskDialogStandardResult.OK) return;
            if (dialog.Content is not AddOrChangeTask project) return;
            var result = project.Done();
            if (string.IsNullOrEmpty(result.Description))
            {
                view.NotificationShow("添加任务", "添加失败", NotificationType.Error);
                return;
            }

            using var proj = new ProjectServer(main.Jwt);
            result.Project = new ProjectModel() { Id = model.Project.Id };
            result = await proj.CreateOrUpdateTask(result);
            if (result == null)
            {
                view.NotificationShow("添加任务", "添加失败", NotificationType.Error);
                return;
            }

            var clone = model.Project.Clone();
            clone.Tasks.Add(result);
            var index = model.Projects.IndexOf(model.Project);
            model.Projects[index] = clone;
            model.Project = clone;
            view.NotificationShow("添加任务", "添加成功");
        };
        await td.ShowAsync();
    }

    private async void TaskChangeClick(object? sender, RoutedEventArgs e)
    {
        var main = ViewOpera.GetView<MainView>(this);
        if (main == null) return;
        var view = ViewOpera.GetView<MainWindow>(main);
        if (view == null) return;
        if (sender is not Control control) return;
        if (control.DataContext is not TaskModel gantt) return;
        if (gantt.Users.All(x => x.UserId != main.User.UserId)) return;
        var td = new TaskDialog
        {
            Title = "更改任务",
            Content = new AddOrChangeTask(gantt),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CloseButton
            },
            XamlRoot = (Visual)VisualRoot!
        };

        td.Closing += async (dialog, args) =>
        {
            if ((TaskDialogStandardResult)args.Result != TaskDialogStandardResult.OK) return;
            if (dialog.Content is not AddOrChangeTask project) return;
            var result = project.Done();
            gantt.Update(result);
            using var proj = new ProjectServer(main.Jwt);
            if (await proj.CreateOrUpdateTask(gantt) != null)
                view.NotificationShow("更改任务", "更改成功");
            else
                view.NotificationShow("更改任务", "更改失败", NotificationType.Error);
        };
        await td.ShowAsync();
    }

    private async void RemoveGanttClick(object? sender, RoutedEventArgs e)
    {
        var main = ViewOpera.GetView<MainView>(this);
        if (main == null) return;
        var view = ViewOpera.GetView<MainWindow>(main);
        if (view == null) return;
        if (DataContext is not ProjectViewModel model) return;
        if (sender is not Control control) return;
        var clone = model.Project.Clone();
        if (control.DataContext is not TaskModel gantt) return;
        if (gantt.Users.Any(x => x.UserId != main.User.UserId)) return;
        using var proj = new ProjectServer(main.Jwt);
        if (await proj.DeleteTask(gantt.Id))
        {
            clone.Tasks.Remove(gantt);
            var index = model.Projects.IndexOf(model.Project);
            model.Projects[index] = clone;
            model.Project = clone;
            view.NotificationShow("删除任务", "删除成功");
        }
        else
            view.NotificationShow("删除任务", "删除失败", NotificationType.Error);
    }

    private async void ShowUserClick(object? sender, RoutedEventArgs e)
    {
        var main = ViewOpera.GetView<MainView>(this);
        if (main == null) return;
        var view = ViewOpera.GetView<MainWindow>(main);
        if (view == null) return;
        if (DataContext is not ProjectViewModel model) return;
        var td = new TaskDialog
        {
            Title = "查看成员",
            Content = new ShowUsers(model.Project.Staffs),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                TaskDialogButton.OKButton
            },
            XamlRoot = (Visual)VisualRoot!
        };
        await td.ShowAsync();
    }

    private async void UpdateProjectClick(object? sender, RoutedEventArgs e)
    {
        var main = ViewOpera.GetView<MainView>(this);
        if (main == null) return;
        var view = ViewOpera.GetView<MainWindow>(main);
        if (view == null) return;
        if (sender is not Control control) return;
        if (control.DataContext is not ProjectModel model) return;
        var td = new TaskDialog
        {
            Title = "更改项目",
            Content = new UpdateProject(model),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                TaskDialogButton.OKButton,
                TaskDialogButton.CloseButton
            },
            XamlRoot = (Visual)VisualRoot!
        };

        td.Closing += async (dialog, args) =>
        {
            if ((TaskDialogStandardResult)args.Result != TaskDialogStandardResult.OK) return;
            if (dialog.Content is not UpdateProject project) return;
            var result = project.Done();
            using var proj = new ProjectServer(main.Jwt);
            if (await proj.CreateOrUpdateProject(result) != null)
                view.NotificationShow("更改项目", "更改成功");
            else
                view.NotificationShow("更改项目", "更改失败", NotificationType.Error);
        };
        await td.ShowAsync();
    }

    private async void TaskDoneClick(object? sender, RoutedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not TaskModel gantt) return;
        var main = ViewOpera.GetView<MainView>(this);
        if (main == null) return;
        var view = ViewOpera.GetView<MainWindow>(main);
        if (view == null) return;
        gantt.Status = !gantt.Status;
        using var proj = new ProjectServer(main.Jwt);
        if (await proj.CreateOrUpdateTask(gantt) != null)
            view.NotificationShow("完成任务", "更改成功");
        else
            view.NotificationShow("完成任务", "更改失败", NotificationType.Error);
    }
}